import { ArgumentsHost, BadRequestException, Catch, ExceptionFilter, HttpException, Logger, NotFoundException } from '@nestjs/common';
import { ApiException } from 'src/exception/api.exception';
import { ResultBean } from 'src/types';

@Catch()
export class GlobalExceptionFilter<T extends Error> implements ExceptionFilter {

  private readonly logger = new Logger(GlobalExceptionFilter.name);

  catch(e: T, host: ArgumentsHost) {
    let contextHost = host.switchToHttp();
    let res = contextHost.getResponse();
    let req = contextHost.getRequest();

this.logger.error(`全局异常处理器: 
===========Request==============
URL: ${req.method} ${req.url}
Params:${JSON.stringify(req.params)}
Querys:${JSON.stringify(req.query)}
Body:${JSON.stringify(req.body)}
============ErrorContext==================
${JSON.stringify(e,null,4)}
=============Stack========================
${e?.stack}`)

                            
    if(e instanceof HttpException){
        const exception = e as HttpException;
     
    
        if (exception instanceof ApiException) {
          res.json(ResultBean.error((exception.getResponse() as any).msg, (exception.getResponse() as any).code))
          
        } else if (exception instanceof BadRequestException) {
          res.json(ResultBean.error((exception.getResponse() as any).message.join(","), (exception.getResponse() as any).statusCode))
    
        } else if (exception instanceof NotFoundException) {
          res.json(ResultBean.error((exception.getResponse() as any).message, (exception.getResponse() as any).statusCode))
        } 

        return;
    }

    res.json(ResultBean.error("发生未知异常"))

  }
}
